import { Component, OnInit } from '@angular/core';


import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam,NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';

import { saveAs } from 'file-saver';
import * as XLSX from "xlsx";

@Component({
    selector: 'xlsx-component',
    templateUrl: './xlsx.component.html',
    styleUrls: ['./xlsx.component.css']
})
export class XlsxComponent implements OnInit {

    value?: string;
    constructor(
        private msg: NzMessageService
    ) {
    }

    ngOnInit() {

        
    }

    beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
      return new Observable((observer: Observer<boolean>) => {
        const isJpgOrPng = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if (!isJpgOrPng) {
          this.msg.error('You can only upload JPG file!');
          observer.complete();
          return;
        }
        const isLt2M = file.size! / 1024 / 1024 < 5;
        if (!isLt2M) {
          this.msg.error('Image must smaller than 5MB!');
          observer.complete();
          return;
        }
        this.readerData(file);
        observer.next(isJpgOrPng && isLt2M);
        observer.complete();
      });
    };

    generateData = ({ header, results })=> {
      console.log(header);
      console.log(results);
    }

    readerData = (rawFile) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    }

    getHeaderRow = (sheet)=> {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    }

    handleChange(info: NzUploadChangeParam): void {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          this.msg.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
          this.msg.error(`${info.file.name} file upload failed.`);
        }
    }
}